package com.example.task.scheduler;

import com.example.task.entity.HttpTask;
import com.example.task.service.TaskService;
import jakarta.annotation.PostConstruct;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

@Component
public class TaskScheduler {

    @Autowired
    TaskService service;

    private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);
    private final Map<Long, ScheduledFuture<?>> scheduledTasks = new ConcurrentHashMap<>();

    @PostConstruct
    public void scheduleAll() {
        List<HttpTask> tasks = service.getActiveTasks();
        for (HttpTask task : tasks) {
            if (task.isActive()) {
                schedule(task);
            }
        }
    }

    public void schedule(HttpTask task) {
        cancel(task.getId());  // 防止重复调度

        Runnable runnable = () -> {
            try {
                sendHttp(task);
            } catch (Exception e) {
                System.err.println("任务执行失败：" + e.getMessage());
                e.printStackTrace();
            }
        };

        ScheduledFuture<?> future = executor.scheduleAtFixedRate(
                runnable, 0, task.getIntervalSeconds(), TimeUnit.SECONDS);

        scheduledTasks.put(task.getId(), future);
    }

    public void cancel(Long taskId) {
        ScheduledFuture<?> future = scheduledTasks.get(taskId);
        if (future != null) {
            future.cancel(true);
            scheduledTasks.remove(taskId);
            System.out.println("已取消任务 ID = " + taskId);
        }
    }



    private void sendHttp(HttpTask task) throws Exception {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            String method = task.getMethod().toUpperCase();
            String contentType = task.getContentType() != null ? task.getContentType() : "application/json;charset=GB2312";
            Charset charset = extractCharset(contentType);

            HttpResponse response;

            if ("POST".equals(method)) {
                HttpPost post = new HttpPost(task.getUrl());
                post.setHeader("Content-Type", contentType);
                StringEntity entity = new StringEntity(task.getParams(), charset);
                post.setEntity(entity);
                response = httpClient.execute(post);
            } else if ("GET".equals(method)) {
                HttpGet get = new HttpGet(task.getUrl());
                get.setHeader("Content-Type", contentType);
                response = httpClient.execute(get);
            } else {
                throw new UnsupportedOperationException("不支持的请求方式：" + method);
            }

            int statusCode = response.getStatusLine().getStatusCode();
            String responseContent = EntityUtils.toString(response.getEntity(), charset);

            System.out.println("任务 [" + task.getName() + "] 执行完成，状态码: " + statusCode);
            System.out.println("响应内容: " + responseContent);
        }
    }

    /**
     * 从 Content-Type 中提取编码（默认返回 GB2312）
     */
    private Charset extractCharset(String contentType) {
//        try {
//            String[] parts = contentType.split(";");
//            for (String part : parts) {
//                if (part.trim().toLowerCase().startsWith("charset=")) {
//                    return Charset.forName(part.trim().split("=")[1]);
//                }
//            }
//        } catch (Exception ignored) {
//        }
        return Charset.forName("GB2312");
    }
}
